package com.fanrui.code.handle;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.fanrui.code.chess.ChessTableManager;
import com.fanrui.code.chess.ITable;
import com.fanrui.code.common.annotation.Handle;
import com.fanrui.code.dao.EParameterType;
import com.fanrui.code.dao.ParameterConfigManager;
import com.fanrui.code.entity.Family;
import com.fanrui.code.family.FamilyDao;
import com.fanrui.code.family.FamilyEntity;
import com.fanrui.code.family.FamilyManager;
import com.fanrui.code.family.FamilyMember;
import com.fanrui.code.message.RequestContext;
import com.fanrui.code.player.Player;
import com.fanrui.code.player.Player.OperationType;
import com.fanrui.code.util.PlayerData;
import com.fanrui.code.util.PlayerLogUtil;
import com.fanrui.code.util.PlayerLogUtil.PlayerOpertionType;
import com.fanrui.code.util.logger.Stdout;
import com.fanrui.proto.cmd.ClubItem;
import com.fanrui.proto.cmd.MahjongRoomInfo;
import com.fanrui.proto.cmd.PlayersItem;
import com.fanrui.proto.cmd.ReqAMemberUpgradePosition;
import com.fanrui.proto.cmd.ReqChangeClubName;
import com.fanrui.proto.cmd.ReqClubMahjongTables;
import com.fanrui.proto.cmd.ReqEnterClub;
import com.fanrui.proto.cmd.ReqGetMemebers;
import com.fanrui.proto.cmd.ReqQueryPlayerClub;
import com.fanrui.proto.cmd.ReqSearchSomeOne;
import com.fanrui.proto.cmd.ResAMemberUpgradePosition;
import com.fanrui.proto.cmd.ResChangeClubName;
import com.fanrui.proto.cmd.ResClubMahjongTables;
import com.fanrui.proto.cmd.ResEnterClub;
import com.fanrui.proto.cmd.ResGetMemebers;
import com.fanrui.proto.cmd.ResQueryPlayerClub;
import com.fanrui.proto.cmd.ResQueryPlayerClub.Result;
import com.fanrui.proto.cmd.ResSearchSomeOne;

/**
 * 俱乐部命令
 * 
 * @author Administrator
 *
 */
public class ClubHandle {

	/**
	 * 修改职位
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void clubMemberUpgradePosition(Player player, RequestContext context, ReqAMemberUpgradePosition req) {
		ResAMemberUpgradePosition.Builder res = ResAMemberUpgradePosition.newBuilder();
		String result = FamilyManager.getInstance().setPlayerClubJob(player, req);
		if (result.equals("UnPermission")) {
			res.setResult(com.fanrui.proto.cmd.ResAMemberUpgradePosition.Result.LimitedAuthority);
		}else if (result.equals("Success")) {
			res.setResult(com.fanrui.proto.cmd.ResAMemberUpgradePosition.Result.Success);
		}else {
			res.setResult(com.fanrui.proto.cmd.ResAMemberUpgradePosition.Result.UnUsed);
		}
		
		context.sendResponse(res.build());
	}

	/**
	 * 根据Id或昵称查询俱乐部成员
	 * 
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void searchSomeOneMember(Player player, RequestContext context, ReqSearchSomeOne req) {
		ResSearchSomeOne.Builder res = ResSearchSomeOne.newBuilder();
		FamilyEntity fm = FamilyDao.getInstance().findById(player.getFamilyId());
		if (fm != null) {
			FamilyMember member = fm.getMemberByIdOrNickname(req.getIdOrNickname());
			if (member != null) {
				res.setPlayer(member.toClubPlayers());
			}
		}
		context.sendResponse(res.build());
		return;
	}

	/**
	 * 进入俱乐部
	 * 
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void enterClub(Player player, RequestContext context, ReqEnterClub req) {
		ResEnterClub.Builder res = ResEnterClub.newBuilder();
		// 查询玩家是否在某一个俱乐部中
		FamilyEntity fm = FamilyDao.getInstance().findById(req.getClubId());
		if (fm == null) {
			// 俱乐部不存在
			res.setResult(ResEnterClub.Result.NoQuerying);
			// fm.getFamilyMemberById(player.getId()) == null
		} else if (!player.checkHavaClub(req.getClubId())) {
			// 该玩家还没有加入该俱乐部
			res.setResult(ResEnterClub.Result.UnUsed);
		} else {
			// fm.enter(player);
			// 俱乐部信息
//			Collection<ITable> tables = ChessTableManager.getInstance().getClubTables(fm.getId());
//			List<ClubGameRoom> list = new ArrayList<ClubGameRoom>();
			List<PlayersItem> allPlayers = FamilyEntity.toClubPlayer(fm.getMembers());
			player.setFamilyData(fm);
			player.save();
			res.addAllPlayers(allPlayers);
//			if (tables != null) {
//				for (ITable table : tables) {
//					ClubGameRoom.Builder cr = ClubGameRoom.newBuilder();
//					cr.setRoomID(table.getID());
//					cr.setRoomType(table.getGameType());
//					Collection<Long> playerIds = table.getPlayerIds();
//					if (playerIds != null && !playerIds.isEmpty() && allPlayers != null && !allPlayers.isEmpty()) {
//						for (long playerId : playerIds) {
//							for (PlayersItem pi : allPlayers) {
//								if (playerId == pi.getUserID()) {
//									cr.addPlayers(pi);
//								}
//							}
//						}
//					}
////					if (table instanceof AbstractMahjongTable<?>) {//getGaStyle()
////						cr.setGaStyle(((AbstractMahjongTable<?>) table).getGameRules().getRoomConfig());
////					}
////					if (table instanceof AbstractThreePokerTable<?>) {
////						cr.setSgaStyle(((AbstractThreePokerTable<?>) table).getGameRules().getCustomConfig());
////					}
////					list.add(cr.build());
//				}
//			}
//			res.addAllRooms(list);
			res.setClubId(fm.getId());
			res.setOwerId(fm.getOwer().getId());
			res.setOwerDiamond(fm.getOwer().getMoney());
			res.setTitle(fm.getFamilyName());
			res.setBulletin(fm.getFamilyNotice());
			res.setResult(ResEnterClub.Result.Success);
		}
		ResEnterClub cll = res.build();
		context.sendResponse(cll);
//		System.out.println(cll.toByteArray().length);
	}
//
//	/**
//	 * 俱乐部创建房间的每日消耗
//	 * 
//	 * @param player
//	 * @param context
//	 * @param req
//	 */
//	@Handle
//	public void getDayCost(Player player, RequestContext context, ReqGetDayCost req) {
//		ResGetDayCost.Builder res = ResGetDayCost.newBuilder();
//		String date = DateUtil.getDateToStringDay(new Date());
//		int dayCost = PlayerLogDao.getInstance().getClubDayCreateRoomCost(player.getId(), req.getClubId(), date);
//		res.setDayCost(dayCost);
//		context.sendResponse(res.build());
//	}

	/**
	 * 俱乐部改名
	 * 
	 * @param player
	 * @param context
	 * @param Club
	 */
	@Handle
	public void changeClubName(Player player, RequestContext context, ReqChangeClubName req) {
		ResChangeClubName.Builder res = ResChangeClubName.newBuilder();

		// 不是族长不能改名
		FamilyEntity club = player.getFamilyData();
		if (club == null) {
			res.setResult(com.fanrui.proto.cmd.ResChangeClubName.Result.UnUsed);
			context.sendResponse(res.build());
			return;
		}
		if (player.getId() != club.getOwer().getId()) {
			res.setResult(com.fanrui.proto.cmd.ResChangeClubName.Result.UnUsed);
			context.sendResponse(res.build());
			return;
		}

		// 俱乐部改名需要消耗的金币数量
		long needGold = ParameterConfigManager.getInstance().getIntParameter(EParameterType.clubChangeNameNeedGold);
		if (player.getGold() < needGold) {
			res.setResult(com.fanrui.proto.cmd.ResChangeClubName.Result.UnGold);
			context.sendResponse(res.build());
			return;
		}

		// 俱乐部名称不能重复
		String name = req.getName();
		if (name == null || "".equals(name) || FamilyDao.getInstance().familyIsExist(req.getName())) {
			res.setResult(com.fanrui.proto.cmd.ResChangeClubName.Result.Repeat);
			context.sendResponse(res.build());
			return;
		}

		// 修改俱乐部名字并扣除玩家金币
		club.setFamilyName(name);
		Family family = FamilyDao.getInstance().selectByPrimaryKey(club.getId());
		if (family != null) {
			family.setFamilyName(name);
			FamilyDao.getInstance().updateFamily(family);
		}
		PlayerData data = new PlayerData(player);
		player.operationCost(com.fanrui.proto.cmd.CurrencyType.C_Gold, needGold, OperationType.Minus);
		PlayerLogUtil.log(player, PlayerOpertionType.ChangeClubName, (int)needGold, "修改家族名称", data);
		Stdout.GET().info("族长【" + player.getId() + "】修改家族【" + club.getId() + "】名称为" + name + "消耗金币【" + needGold + "】");

		res.setResult(com.fanrui.proto.cmd.ResChangeClubName.Result.Success);
		context.sendResponse(res.build());
	}

	/**
	 * 查询玩家所在俱乐部
	 * 
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void selectPlayerClub(Player player, RequestContext context, ReqQueryPlayerClub req) {
		ResQueryPlayerClub.Builder res = ResQueryPlayerClub.newBuilder();
		// 根据关键字查询
		List<Family> familys = FamilyDao.getInstance().dbFindByFamilyName(req.getNameKeyWord());

		List<FamilyEntity> clubList = new ArrayList<FamilyEntity>();
		try {
			// 根据家族id查询
			FamilyEntity fm = FamilyDao.getInstance().findById(Integer.parseInt(req.getNameKeyWord()));
			if (fm != null) {
				if (req.getIsQueryAll()) {
					ClubItem info = fm.toClubItem();
					res.addClubItems(info);
					res.setResult(Result.Success);
				} else {
					if (fm.getMembers().containsKey(player.getId())) {
						ClubItem info = fm.toClubItem();
						res.addClubItems(info);
						res.setResult(Result.Success);
					}
				}
			}
		} catch (Exception e) {

		}
		if (familys != null && familys.size() > 0) {
			if (req.getIsQueryAll()) {
				for (Family f : familys) {
					clubList.add(new FamilyEntity(f));
				}
			} else {
				for (Family f : familys) {
					FamilyEntity entity = new FamilyEntity(f);
					if (entity.getMembers().containsKey(player.getId())) {
						clubList.add(entity);
					}
					// if (player.getClubList() != null && !player.getClubList().isEmpty()) {
					// for (FamilyEntity club : player.getClubList().values()) {
					// if (f.getId() == club.getId()) {
					// clubList.add(club);
					// }
					// }
					// }
				}
			}

			res.addAllClubItems(FamilyEntity.toClubItem(clubList));
			res.setResult(Result.Success);
		} else {
			if (res.getResult() != Result.Success)
				res.setResult(Result.NoQuerying);
		}
		context.sendResponse(res.build());
	}

	/**
	 * 获取成员
	 * 
	 * @param player
	 * @param context
	 * @param req
	 *            void
	 */
	@Handle
	public void getMemebers(Player player, RequestContext context, ReqGetMemebers req) {
		FamilyEntity fe = FamilyDao.getInstance().findById(req.getClubId());
		ResGetMemebers.Builder res = ResGetMemebers.newBuilder();
		int pageSize = 5;
		if (fe != null) {
			int startIndex = req.getPageIndex() * pageSize;
			int endIndex = (req.getPageIndex() + 1) * pageSize;
			List<PlayersItem> items = FamilyEntity.toClubPlayer(fe.getMembers());
			if (!items.isEmpty()) {
				for (int i = startIndex; i < items.size() && i < endIndex; i++) {
					res.addPlayers(items.get(i));
				}
			}
		}
		context.sendResponse(res.build());
	}
	
	/**
	 * 获取一个俱乐部的麻将房间
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void getTables(Player player, RequestContext context, ReqClubMahjongTables req) {
		ResClubMahjongTables.Builder res = ResClubMahjongTables.newBuilder();
		// 俱乐部房间
		Collection<ITable> tables = ChessTableManager.getInstance().getClubTables(req.getClubId());
		List<MahjongRoomInfo> rooms = new ArrayList<MahjongRoomInfo>();
		if(tables != null && !tables.isEmpty()) {
			for (ITable table : tables) {
				rooms.add((MahjongRoomInfo)table.toCmd());
			}
		}
		context.sendResponse(res.addAllRooms(rooms).build());
	}
	
}
